package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.ReprotMapper;
import com.sky.service.ReprotService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static java.lang.System.out;

@Service
public class ReprotServiceImpl implements ReprotService {
    @Autowired
    private ReprotMapper reprotMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 销售额统计
     * 1.根据开始日期和结束日期 new一个集合  放入全部日期
     * 2.查询出每个日期的营业额
     * 3.封装返回数据
     *
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //根据开始日期和结束日期 new一个集合  放入全部日期
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //查询出每个日期的营业额
        ArrayList<Double> turnover = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status",Orders.COMPLETED);
            Double dayTurnOver = reprotMapper.queryDayTurnOver(map);

            turnover.add(dayTurnOver);
        }

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnover, ","))
                .build();


    }

    /**
     * 用户统计
     * 1.根据开始日期和结束日期 new一个集合  放入全部日期
     * 2.查询出每天所有的用户
     * 3.查询出当天新建的用户
     *
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //根据开始日期和结束日期 new一个集合  放入全部日期
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //2.查询出每天所有的用户
        List<Integer> newUserList = new ArrayList<>(); //新增用户数
        List<Integer> totalUserList = new ArrayList<>(); //总用户数
        HashMap<Object, Object> map = new HashMap<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            if (map.get("begin")!=null){
                map.remove("begin");
            }
            map.put("end", endTime);
            Integer totalUser = reprotMapper.queryUsers(map);
            map.put("begin", beginTime);
            Integer newUser = reprotMapper.queryUsers(map);
            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    /**
     * 订单统计
     * 1.根据开始日期和结束日期 new一个集合  放入全部日期
     * 2.查询所有订单
     * 3.查询所有有效订单
     * 4.查询完成率
     * 2.查询每日订单总数
     * 3.查询每日有效订单数
     *
     * @return
     */
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        //根据开始日期和结束日期 new一个集合  放入全部日期
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        HashMap<Object, Object> map = new HashMap<>();

        //查询每日全部订单和有效订单
        ArrayList<Integer> orderCountList = new ArrayList<>();
        ArrayList<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            map.put("end",endTime);
            map.put("begin",beginTime);
            map.put("status",null);
            Integer orderCount = reprotMapper.queryOrders(map);
            orderCountList.add(orderCount);
            map.put("status", Orders.COMPLETED);
            Integer validOrderCount = reprotMapper.queryOrders(map);
            validOrderCountList.add(validOrderCount);
        }
        //查询订单总数
/*        map.put("end", end);
        map.put("begin",dateList.get(0));
        map.put("status",null);
        Integer totalOrderCount = reprotMapper.queryOrders(map);*/
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //查询全部有效订单
/*        map.put("status", Orders.COMPLETED);
        Integer validOrderCount = reprotMapper.queryOrders(map);*/

        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //计算订单完成率
        Double orderCompletionRate = 0.0;
        double v = validOrderCount.doubleValue();
        if (totalOrderCount!=0){
             orderCompletionRate = v / totalOrderCount;
        }




         return OrderReportVO.builder()
                 .dateList(StringUtils.join(dateList,","))
                 .validOrderCount(validOrderCount)
                 .orderCountList(StringUtils.join(orderCountList,","))
                 .totalOrderCount(totalOrderCount)
                 .validOrderCountList(StringUtils.join(validOrderCountList,","))
                 .orderCompletionRate(orderCompletionRate)
                 .build();

    }

    /**
     * 销量前十统计
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        Map map = new HashMap<>();
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        ArrayList<GoodsSalesDTO> list = reprotMapper.top10(map);
/*        ArrayList<String> nameList = new ArrayList<>();
        ArrayList<String> numberList = new ArrayList<>();
        for (GoodsSalesDTO goodsSalesDTO : list) {
            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getNumber().toString());
        }*/

        List<String> nameList = list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        BusinessDataVO businessData = workspaceService.businessDate(LocalDateTime.
                                        of(begin,LocalTime.MIN),LocalDateTime.of(end,LocalTime.MAX));
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于提供好的模板文件创建一个新的Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //获得Excel文件中的一个Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue(begin +"至" +end);
            XSSFRow row = sheet.getRow(3);
            //获取单元格
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //准备明细数据
                businessData = workspaceService.businessDate(LocalDateTime.of(date,LocalTime.MIN),LocalDateTime.of(date,LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            //关闭资源
            outputStream.flush();
            outputStream.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
